﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Net.NetworkInformation;
using System.IO;

namespace Room
{
    class Core:Commands
    {
        //Encoding enc = Encoding.GetEncoding(866);

        static public bool started = false; //запущен ли сервер или нет

        static public int cClients = Convert.ToInt32(Config.GetConfig("Net", "cClients"));

        static public IPAddress ip;

        static public bool isInt(string kint)
        {
            try
            {
                int n = Convert.ToInt32(kint);
                return true;
            }
            catch (FormatException)
            {
                return false;
            }
        }

        static public bool ping(string host)
        {
            Ping pingSender = new Ping();
            try
            {
                PingReply reply = pingSender.Send(host);
                string b = "";
                for (int i = 0; i < reply.Buffer.Length; ++i) b += reply.Buffer[i].ToString();
                if (b == "") write(3, "[Нету ответа от ICMP]"); else 
                write(3, "[Ответ от ICMP] " + b);
                if (reply.Status == IPStatus.Success)
                {
                    write(3, "[ping] Пакеты успешно отправлены на хост \"" + host + "\".");
                    return true;
                }
                else
                {
                    write(3, "[ping] Хост \"" + host + "\" не отвечает.");
                    return false;
                }

            }
            catch (SocketException)
            {
                write(1, "[ping] Обработан SocketException.");
                return false;
            }
            catch (PingException)
            {
                write(1, "[ping] Обработан PingException.");
                return false;
            }
        }

        static public bool Internet()
        {
            Ping pingSender = new Ping();
            bool inet = false;
            try
            {
                ip = Dns.GetHostAddresses("moi-ip.ru")[0];
                PingReply reply = pingSender.Send(ip.ToString());
                string b = "";
                for (int i = 0; i < reply.Buffer.Length; ++i) b += reply.Buffer[i].ToString();
                write(3, "[ResvData ICMP] " + b);
                inet = reply.Status == IPStatus.Success;
            }
            catch (SocketException)
            {
                write(3, "[Internet] SocketException. Return False.");
                inet = false;
            }
            if (inet) write(3, "[Internet] Connected.");else
                write(3, "[Internet] Not Connected.");
            return inet;
        }

        /// <summary>
        /// Получение данных о данном компьютере из Интернета (парсер), если метод Internet() возвращает True.
        /// Данные: [0]IP, [1]Прокси, [2]Провайдер, [3]Страна.</summary>
        /// <returns></returns>
        static public string[] getDataFromNet()
        {
            write(3, "Начинаю сбор данных из Интернета об этой машине...");
            string[] re = new string[4];
            try
            {
                WebRequest req = WebRequest.Create("http://moi-ip.ru/");
                Stream stream = req.GetResponse().GetResponseStream();
                StreamReader read = new StreamReader(stream, Encoding.GetEncoding(1251));
                string t = "";
                string buf = "";
                while (!read.EndOfStream)
                {
                    t = read.ReadLine();
                    if (t == "                        		<td class=\"f-left\">Ваш IP</td>")
                    {
                        buf = read.ReadLine();
                        buf = buf.Replace("<td class=\"f-right\"><span>", " ");
                        buf = buf.Replace("</span></td>", " ");
                        buf = buf.Trim();
                        re[0] = buf;
                    }
                    if (t == "                        		<td class=\"f-left-noop\">Proxy</td>")
                    {
                        buf = read.ReadLine();
                        buf = buf.Replace("<td class=\"f-right\"><span class=\"black\">", " ");
                        buf = buf.Replace("</span></td>", " ");
                        buf = buf.Trim();
                        if (buf == "&mdash;") re[1] = "(none)"; else re[1] = buf;
                    }
                    if (t == "                        		<td class=\"f-left-noop\">Провайдер</td>")
                    {
                        buf = read.ReadLine();
                        buf = buf.Replace("<td class=\"f-right\"><span class=\"black\">", " ");
                        buf = buf.Replace("</span></td>", " ");
                        buf = buf.Trim();
                        re[2] = buf;
                    }
                    if (t == "                        		<td class=\"f-left-noop\">Страна</td>")
                    {
                        t = read.ReadLine();
                        buf = read.ReadLine();
                        buf = buf.Replace("<td class=\"f-right\"><span class=\"black\">", " ");
                        buf = buf.Replace("</span></td>", " ");
                        buf = buf.Trim();
                        re[3] = buf;
                    }
                }
            }
            catch (WebException)
            {
                write(1, "[getDataFromNet] Ошибка обработана. Catch: WebException.");
                re[0] = "(none)";
            }
            return re;
        }

        static public bool isHost(string host)
        {      
            if (!IPAddress.TryParse(host, out ip)) return false; return true;
        }

        private const int notP = 2;
        static private int[] notPort = new int[notP] { 80, 8080 };

        static public bool isPort(string p)
        {
            try
            {
                uint port = (uint)Convert.ToInt32(p);
                int ind = -1;
                for (int i = 0; i < notP; ++i) if (notPort[i] == port) ind = i;
                if (port > 65535) return false;
                if (ind != -1) return false;
                return true;
            }
            catch (FormatException)
            {
                ConsoleHandle.write(1, "Во время проверки порта возникла ошибка (FormatException).");
                return false;
            }
        }
    }
}
